package com.hunter.lucene.util.search.query;

import java.io.IOException;
import java.util.Comparator;
import java.util.PriorityQueue;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Scorer;

/**
 * 此类将一次收集所有的命中结果，并对其进行默认排序（相关度）。
 * @author bastengao
 *
 */
public class AllScoreSortedCollector extends Collector {

	private PriorityQueue<ScoreDoc> hits = new PriorityQueue<ScoreDoc>(32,
			new ScoreDocComparator());
	private int docBase = 0;
	private Scorer currectScore = null;

	@Override
	public boolean acceptsDocsOutOfOrder() {
		return false;
	}

	@Override
	public void collect(int docId) throws IOException {
		hits.offer(new ScoreDoc(docBase+docId, currectScore.score()));
	}

	@Override
	public void setNextReader(IndexReader arg0, int docBase) throws IOException {
		this.docBase = docBase;
	}

	@Override
	public void setScorer(Scorer scorer) throws IOException {
		currectScore = scorer;
	}

	public int size() {
		return hits.size();
	}

	public ScoreDoc poll() {
		return hits.poll();
	}

	private static class ScoreDocComparator implements Comparator<ScoreDoc> {

		@Override
		public int compare(ScoreDoc o1, ScoreDoc o2) {
			return (int) (Math.signum(o2.score - o1.score));
		}

	}

}
